<?php
/**
 * Created by PhpStorm.
 * User: sunzexin
 * Date: 2017/12/28
 * Time: 14:57
 */

namespace App\Http\Logics\MiniProgramAdmin;


use App\Party;
use App\PartySignUp;
use App\Users;
use Faker\Provider\DateTime;
use App\Http\Logics\BaseLogic;
class PartyLogic extends BaseLogic
{
    /**
     * 创建活动
     * @param $data 活动信息
     * @return mixed 返回新创建活动的ID
     */
    public static function createParty($data)
    {
        try{
            $response = self::getPartnerIdByLoginSession($data['loginSession']);
            if ($response->code) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            $partner_id = $response->data;
            $party = new Party();
            $party->partner_id = $partner_id;
            $url = $data['cover'] . "?imageInfo";
            // 处理图片
            $rs = dealHttp($url);
            $width = $rs->width;
            $height = $rs->height;
            $party->cover_width = $width;
            $party->cover_height = $height;
            $party->cover = $data['cover'];
            $party->name = $data['name'];
            $party->summary = $data['summary'];
            $party->user_count = $data['user_count'];
            $party->start_date = $data['start_date'];
            $party->end_date = $data['end_date'];
            $party->start_time = $data['start_time'];
            $party->end_time = $data['end_time'];
            $party->address = $data['address'];
            $party->mobile = $data['mobile'];
            $party->price = $data['price'];
            $party->party_category_id = $data['party_category_id'];
            if (!$party->save()) {
                return self::response(self::OBJECT_SAVE_FAIL);
            }
            return self::response(self::SUCCESS, $party->id);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 一间咖啡馆平台创建活动
     * @param $data 活动信息
     * @return mixed 返回新创建活动的ID
     */
    public static function createParty2($data)
    {
        try{
            $response = self::getUserIdByLoginSession($data['loginSession']);
            if ($response->code){
                return self::response($response->code);
            }
            $user_id = $response->data;
            $party = new Party();
            $party->cafe_id = $data['cafe_id'];
            $party->user_id = $user_id;
            $url = $data['cover'] . "?imageInfo";
            // 处理图片
            $rs = dealHttp($url);
            $width = $rs->width;
            $height = $rs->height;
            $party->cover_width = $width;
            $party->cover_height = $height;
            $party->cover = $data['cover'];
            $party->name = $data['name'];
            $party->summary = $data['summary'];
            $party->user_count = $data['user_count'];
            $party->start_date = $data['start_date'];
            $party->end_date = $data['end_date'];
            $party->start_time = $data['start_time'];
            $party->end_time = $data['end_time'];
            $party->address = $data['address'];
            $party->mobile = $data['mobile'];
            $party->price = $data['price'];
            $party->party_category_id = $data['party_category_id'];
            if (!$party->save()) {
                return self::response(self::OBJECT_SAVE_FAIL);
            }
            return self::response(self::SUCCESS, $party->id);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 创建活动
     * @param $data 活动信息
     * @return mixed 创建结果
     */
    public static function updateParty($data)
    {
        try{
            $response = self::getPartnerIdByLoginSession($data['loginSession']);
            if ($response->code) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            $partner_id = $response->data;
            $party = Party::find($data['party_id']);
            $party->partner_id = $partner_id;
            $url = $data['cover'] . "?imageInfo";
            // 处理图片
            $rs = dealHttp($url);
            $width = $rs->width;
            $height = $rs->height;
            $party->cover_width = $width;
            $party->cover_height = $height;
            $party->cover = $data['cover'];
            $party->name = $data['name'];
            $party->summary = $data['summary'];
            $party->user_count = $data['user_count'];
            $party->start_date = $data['start_date'];
            $party->end_date = $data['end_date'];
            $party->start_time = $data['start_time'];
            $party->end_time = $data['end_time'];
            $party->address = $data['address'];
            $party->mobile = $data['mobile'];
            $party->price = $data['price'];
            $party->party_category_id = $data['party_category_id'];
            if (!$party->save()) {
                return self::response(self::OBJECT_SAVE_FAIL);
            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 创建活动
     * @param $data 活动信息
     * @return mixed 创建结果
     */
    public static function updateParty2($data)
    {
        try{
            $party = Party::find($data['party_id']);
            $url = $data['cover'] . "?imageInfo";
            // 处理图片
            $rs = dealHttp($url);
            $width = $rs->width;
            $height = $rs->height;
            $party->cover_width = $width;
            $party->cover_height = $height;
            $party->cover = $data['cover'];
            $party->name = $data['name'];
            $party->summary = $data['summary'];
            $party->user_count = $data['user_count'];
            $party->start_date = $data['start_date'];
            $party->end_date = $data['end_date'];
            $party->start_time = $data['start_time'];
            $party->end_time = $data['end_time'];
            $party->address = $data['address'];
            $party->mobile = $data['mobile'];
            $party->price = $data['price'];
            $party->party_category_id = $data['party_category_id'];
            if (!$party->save()) {
                return self::response(self::OBJECT_SAVE_FAIL);
            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 获取活动列表
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function getPartyList($data)
    {
        try {
            $partner_id = $data['partner_id'];
            $party = Party::where(function ($query) use ($data) {
                if ($data['party_category_id']) {
                    $query->where('party_category_id', $data['party_category_id']);
                }
            })->where('partner_id', $partner_id)->orderBy('id', 'desc')->get()->groupBy('progress');
            if (empty($party)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $party);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 一间咖啡馆平台获取活动列表
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function getPartyList2($data)
    {
        try {
            $query = Party::where(function ($query) use ($data) {
                if (isset($data['cafe_id']) && $data['cafe_id']) {
                    $query->where('cafe_id', $data['cafe_id']);
                }
                if (isset($data['status']) && $data['status'] != ''){
                    $query->where('status', $data['status']);
                }
            })->orderBy('id', 'desc');
            $party = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
            if (empty($party)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $party);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 获取活动普通列表
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function getPartyNormalList($data)
    {
        try {
            $response = self::getPartnerIdByKey($data['key']);
            if ($response->code) {
                return self::response($response->code);
            }
            $partner_id = $response->data;
            $party = Party::where(function ($query) use ($data) {
                if ($data['party_category_id']) {
                    $query->where('party_category_id', $data['party_category_id']);
                }
            })->where('partner_id', $partner_id)->orderBy('id', 'desc')->get();
            if (empty($party)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $party);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 获取活动详情
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function getPartyDetail($data)
    {
        try {
            $party = Party::with(['partyPhoto', 'partySignUp' => function ($query) {
                $query->select(['nickname', 'headimgurl'])->take(10);
            }])->find($data['party_id']);
            $party->is_sign_up = false;
            // 判断用户是否登录
            if (!empty($data['loginSession'])) {
                // 如果登录了，判断用户是否报名该活动
                $response = self::getUserIdByLoginSession($data['loginSession']);
                if ($response->code) {
                    return self::response($response->code);
                }
                $user_id = $response->data;
                $is_sign_up = partySignUp::where('user_id', $user_id)->where('party_id', $data['party_id'])->count();
                $party->is_sign_up = $is_sign_up ? true : false;
                // 返回用户信息
                $party->user_info = Users::select(['id', 'mobile'])->find($user_id);
            }
            if (empty($party)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            // 计算报名中数量
            $party->party_sign_up_num = $party->partySignUp()->count();

            return self::response(self::SUCCESS, $party);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 获取活动详情
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function getPartyDetail2($data)
    {
        try {
            $party = Party::find($data['party_id']);
            if (empty($party)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $party);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 发送活动报名短信通知
     * @param $data 活动信息
     * @return mixed 返回结果
     */
    public static function sendPartySignUpSms($data)
    {
        try {
            // 发送短信通知报名成功
            $party = Party::find($data['party_id']);
            $sign = '【理想书店】';
            $content = '您已成功报名的《' . $party->name . '》活动，将于' . $party->start_date . '至' . $party->end_date . '的' . $party->start_time . '到' . $party->end_time . '，在' . $party->address . '举办，不要忘记参加哦。';
            $sms_data = [
                'mobile' => $data['mobile'],
                'content' => $content,
                'sign' => $sign
            ];
            $response = self::sendSms($sms_data);
            if ($response->code) {
                return self::response(self::SMS_SEND_FAILD);
            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 发送报名通知消息
     * @param $data 活动信息
     * @return mixed 返回结果
     */
    public static function sendPartySignUpSystemNotify($data)
    {
        try {
            $party = Party::find($data['party_id']);

            // 判断活动是否存在
            if (empty($party)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }

            // 通过loginSession获取到用户的openid
            $response = self::getWxAppOpenidByLoginSession($data['loginSession']);
            if ($response->code) {
                return self::response($response->code);
            }
            $wx_app_openid = $response->data;

            // 拼接消息内容
            $content = [
                'keyword1' => [
                    'value' => $party->name,
                    'color' => '#000000'
                ],
                'keyword2' => [
                    'value' => $party->start_date . '至' . $party->end_date . '的' . $party->start_time . '到' . $party->end_time,
                    'color' => '#000000'
                ],
                'keyword3' => [
                    'value' => $party->address,
                    'color' => '#000000'
                ]

            ];

            // 组装请求数组
            $system_notify_data = [
                'touser' => $wx_app_openid,
                'template_id' => 'F6OqlwiSg0d5qeY_7U_c6cgJ3NRV713bcXZ3f0_rIDo',
                'page' => 'pages/module/party/front/detail/detail?party_id=' . $data['party_id'],
                'form_id' => $data['form_id'],
                'data' => $content,
                "emphasis_keyword" => "keyword1.DATA"
            ];

            // 通过loginSession获取AccessToken
            $response = self::getAccessTokenByLoginSession($data['loginSession']);
            if ($response->code) {
                return self::response($response->code);
            }
            $access_token = $response->data;

            // 给用户发送系统通知消息
            $response = self::sendSystemNotify($system_notify_data, $access_token);
            if ($response->code) {
                return self::response($response->code);
            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 报名参加活动
     * @param $data 报名信息
     * @return mixed 返回结果
     */
    public static function signUp($data)
    {
        try {
            $response = self::getUserIdByLoginSession($data['loginSession']);
            if ($response->code) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            $user_id = $response->data;
            // 判断是否已经报名，防止重复报名
            $party_sign_up = PartySignUp::where('user_id', $user_id)->where('party_id', $data['party_id'])->count();
            if ($party_sign_up) {
                return self::response(self::PARTY_SIGN_UP_AGAIN);
            }
            $party_sign_up_data = [
                'user_id' => $user_id,
                'party_id' => $data['party_id']
            ];
            // 创建报名信息
            $response = PartySignUpLogic::createPartySignUp($party_sign_up_data);
            if ($response->code) {
                return self::response($response->code);
            }
            // 发送报名成功的系统通知
//            $response = self::sendPartySignUpSystemNotify($data);
//            if ($response->code) {
//                return self::response($response->code);
//            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function deleteParty($data)
    {
        $party = Party::find($data['party_id']);
        if (empty($party)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        if (!$party->delete()){
            return self::response(self::OBJECT_DELETE_FAILD);
        }
        return self::response(self::SUCCESS);
    }
}